package com.wnxy.eleba.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@CrossOrigin
@RequestMapping("/file")
@Controller
public class FileCrossOriginController {
    @Value("${aliyun.oss.bucketName}")
    String bucketName;
    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;

    private Logger logger=LoggerFactory.getLogger(FileCrossOriginController.class);

    @ResponseBody
    @RequestMapping("/backUpload")
    public String   upload(@RequestParam("file") MultipartFile file) throws IOException {
        OSS build = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String path = DateTime.now().toString("YYYY/MM/dd");
        path=path+"/"+originalFilename;
        logger.warn(path);
        build.putObject(bucketName,path,inputStream);
        build.shutdown();
        String url="https://"+bucketName+"."+endpoint+"/"+path;
        logger.warn(url);
        return url;
    }
}
